import { exec } from 'child_process'
import { BrowserWindow } from 'electron'
import { clipboard, dialog, screen } from 'electron'
import screenshot from 'screenshot-desktop'

export class screenshotService {
  static screenshot_float(_event, imgData: any): any {
    if (imgData && typeof imgData === 'string' && imgData.startsWith('data:image/')) {
      // 直接弹出悬浮窗，图片 base64 需 encodeURIComponent 防止特殊字符丢失
      const safeImgData = encodeURIComponent(imgData)
      const floatWin = new BrowserWindow({
        width: 400,
        height: 300,
        alwaysOnTop: true,
        frame: false,
        transparent: true,
        resizable: true,
        skipTaskbar: true,
        webPreferences: { nodeIntegration: true, contextIsolation: false }
      })
      // 强制置顶到所有层级
      floatWin.setAlwaysOnTop(true, 'screen-saver')
      floatWin.loadURL(
        `data:text/html,<body style="margin:0;background:transparent;"><div style="width:100vw;height:100vh;-webkit-app-region:drag;display:flex;align-items:center;justify-content:center;position:relative;"><button onclick="window.close()" style="position:absolute;top:12px;right:12px;width:32px;height:32px;border:none;border-radius:16px;background:rgba(0,0,0,0.4);color:#fff;font-size:20px;z-index:10;cursor:pointer;-webkit-app-region:no-drag;">×</button><img src='${decodeURIComponent(safeImgData)}' style="max-width:100%;max-height:100%;object-fit:contain;-webkit-app-region:no-drag;cursor:move;"/></div></body>`
      )
      return
    }
    if (process.platform === 'win32') {
      exec('start ms-screenclip:', (err) => {
        if (err) {
          exec('start SnippingTool.exe', () => {})
        }
      })
      let tryCount = 0
      let found = false
      // 记录本次点击前的剪贴板图片
      const prevImageData = clipboard.readImage().toDataURL()
      const timer = setInterval(() => {
        const image = clipboard.readImage()
        const dataUrl = image.toDataURL()
        if (dataUrl && dataUrl !== prevImageData && dataUrl.length > 100) {
          found = true
          clearInterval(timer)
          // 自动保存图片到本地
          // const userDataDir = app.getPath('userData')
          // const screenshotDir = path.join(userDataDir, 'screenshot-float')
          // if (!fs.existsSync(screenshotDir)) {
          //   fs.mkdirSync(screenshotDir, { recursive: true })
          // }
          // const base64 = dataUrl.replace(/^data:image\/png;base64,/, '')
          // const fileName = `${Date.now()}.png`
          // const filePath = path.join(screenshotDir, fileName)
          // fs.writeFileSync(filePath, Buffer.from(base64, 'base64'))
          // 日志调试
          //log.info('截图悬浮捕获到图片, dataUrl长度:', dataUrl.length)
          // 读取图片实际尺寸
          const imgSize = image.getSize()
          let winW = imgSize.width
          let winH = imgSize.height
          // 获取主屏幕可用区域，留出边距
          const { width: maxW, height: maxH } = screen.getPrimaryDisplay().workAreaSize
          const margin = 40
          const maxWinW = Math.max(200, maxW - margin)
          const maxWinH = Math.max(120, maxH - margin)
          let scale = 1
          if (winW > maxWinW || winH > maxWinH) {
            const scaleW = maxWinW / winW
            const scaleH = maxWinH / winH
            scale = Math.min(scaleW, scaleH)
            winW = Math.round(winW * scale)
            winH = Math.round(winH * scale)
          }
          // 创建自适应大小的悬浮窗
          const floatWin = new BrowserWindow({
            width: winW,
            height: winH,
            alwaysOnTop: true,
            frame: false,
            transparent: true,
            resizable: true,
            skipTaskbar: true,
            webPreferences: { nodeIntegration: true, contextIsolation: false }
          })
          // 强制置顶到所有层级
          floatWin.setAlwaysOnTop(true, 'screen-saver')
          global.__screenshotFloatWins.push(floatWin)
          floatWin.on('closed', () => {
            const idx = global.__screenshotFloatWins.indexOf(floatWin)
            if (idx > -1) global.__screenshotFloatWins.splice(idx, 1)
          })
          floatWin.center()
          floatWin.show()
          //log.info('截图悬浮窗口已创建并显示')
          // 彻底修正：HTML 不要任何转义，img src 用双引号，整个 HTML 用 encodeURIComponent
          const html = `<!DOCTYPE html><html><head><meta charset='utf-8'><style>\
    body { margin: 0; background: transparent; }\
    .screenshot-float-wrap {\
      width: 100vw; height: 100vh;\
      -webkit-app-region: drag;\
      display: flex; align-items: center; justify-content: center;\
      position: relative; user-select: none;\
      background: rgba(30, 32, 36, 0.08);\
      box-shadow: 0 4px 32px 0 rgba(0,0,0,0.18);\
      border-radius: 18px;\
    }\
    .screenshot-float-close {\
      position: absolute; top: 16px; right: 16px; width: 36px; height: 36px;\
      border: none; border-radius: 18px; background: rgba(0,0,0,0.32);\
      color: #fff; font-size: 22px; z-index: 9999; cursor: pointer;\
      display: flex; align-items: center; justify-content: center;\
      transition: background 0.18s;\
      -webkit-app-region: no-drag;\
      pointer-events: auto;\
    }\
    .screenshot-float-close:hover { background: rgba(0,0,0,0.5); }\
    .screenshot-float-img {\
      width: 100%; height: 100%; object-fit: contain;\
      pointer-events: auto; user-select: none;\
      box-shadow: 0 2px 16px 0 rgba(0,0,0,0.10); border-radius: 12px;\
      background: #fff; transition: transform 0.12s;\
    }\
    </style></head><body>\
    <div class='screenshot-float-wrap'>\
      <button class='screenshot-float-close' onclick='window.close()'>×</button>\
      <img id='screenshot-img' class='screenshot-float-img' src="${dataUrl}" draggable='false' />\
    </div>\
    <script>\
    let scale = 1;\
    const img = document.getElementById('screenshot-img');\
    document.body.addEventListener('wheel', function(e) {\
      if (e.ctrlKey) return;\
      e.preventDefault();\
      scale += e.deltaY < 0 ? 0.1 : -0.1;\
      scale = Math.max(0.1, Math.min(5, scale));\
      img.style.transform = 'scale(' + scale + ')';\
    }, { passive: false });\
    </script></body></html>`
          floatWin.loadURL('data:text/html,' + encodeURIComponent(html))
        }
        tryCount++
        if (tryCount > 100) {
          // 10秒
          clearInterval(timer)
          if (!found) {
            dialog.showMessageBox({
              type: 'warning',
              message: '未检测到截图图片，请在截图后按 Ctrl+C 复制图片到剪贴板再试一次。'
            })
          }
        }
      }, 100)
      return
    }
    dialog.showMessageBox({
      type: 'info',
      message: '请手动截图后粘贴到应用或剪贴板。'
    })
  }

  public async screenshot_desktop(): Promise<string> {
    const imgBuffer = await screenshot({ format: 'png' })
    return 'data:image/png;base64,' + imgBuffer.toString('base64')
  }
}
